const { Controller } = require('egg');

class CertificateConfigController extends Controller {
  async list() {
    const { service } = this;
    try {
      const result = await service.certificateConfig.list();
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }

  async create() {

    const { ctx, service } = this;
    const { certificateName, certificateRules } = ctx.request.body;
    if (!certificateName ) {
      return this.ctx.helper.error('参数异常');
    }

    let prefix, suffix;

    try {
      prefix = JSON.parse(certificateRules)[0]
      suffix = JSON.parse(certificateRules)[1]
    } catch (error) {

    }

    console.log("prefix", prefix, suffix)

    try {
      const allConfigs = await service.certificateConfig.list();
      for (const config of allConfigs) {

        let rules = []
        try {
          rules = JSON.parse(config.certificateRules);
          console.log("prefix2", rules)


        } catch (error) {

        }
        if (rules[0] === prefix && rules[1] === suffix) {
          return this.ctx.helper.error('已存在重复证书编号生成的规则，不可使用此规则');
        }
      }




      // 如果没有找到重复的配置，继续创建新配置
      const result = await service.certificateConfig.create({
        certificateName,
        certificateRules
      });
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }

  async delete() {
    const { ctx, service } = this;
    const { id } = ctx.request.body;
    try {
      const result = await service.certificateConfig.delete(id);
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }

  async update() {
    const { ctx, service } = this;
    const { id, certificateName, certificateRules } = ctx.request.body;
    if (!id || (!certificateName && !certificateRules) ) {
      return this.ctx.helper.error('参数异常');
    }

    try {
      const result = await service.certificateConfig.update({
        id,
        certificateName,
        certificateRules,
      });
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }
}

module.exports = CertificateConfigController;